﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;


namespace Flame.Reflection
{
    class AllNamespaceAndType
    {
        Namespace _globalNamespace = new Namespace("global");

        public AllNamespaceAndType()
        {
            var allnamespaceAndType = allNamespaceAndType();
            foreach (string s in allnamespaceAndType)
                _globalNamespace.Add(s.Split('.'));
        }

        List<string> allNamespaceAndType()
        {
            try
            {
                var assemblys = AppDomain.CurrentDomain.GetAssemblies();
                var namespaces = new List<string>();
                foreach (Assembly assembly in assemblys)
                {
                    try
                    {
                        namespaces = namespaces.Union<string>(assembly.GetTypes().Select(t => t.FullName).Distinct()).ToList<string>();
                    }
                    catch (System.Exception){}
                }
                return namespaces.Distinct<string>().ToList<string>();
            }
            catch (System.Exception)
            {
                return new List<string>();
            }
        }

        List<string> allNamespaceAndType(Assembly assembly)
        {
            return assembly.GetTypes().Select(t => t.FullName).Distinct().ToList<string>();
        }

        public void Add(Assembly assembly)
        {
            var allnamespaceAndType = allNamespaceAndType(assembly);
            foreach (string s in allnamespaceAndType)
            {
                _globalNamespace.Add(s.Split('.'));
            }
        }

        public List<Class> AvailableNames(IEnumerable<string> names)
        {
            Class currentNamespace = _globalNamespace;
            foreach (string n in names)
            {
                if (currentNamespace is Namespace && (currentNamespace as Namespace).Childs.ContainsKey(n))
                {
                    currentNamespace = (currentNamespace as Namespace).Childs[n];
                }
                else break;
            }

             if (!(currentNamespace is Namespace)) return null;
            return (currentNamespace as Namespace).Childs.Values.ToList<Class>();
        }
    }
}
